<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\SearchLog;

/**
 * 服务项目接口
 * @ApiWeigh (88)
 */
class Service extends Api
{
    protected $noNeedLogin = ['index', 'detail', 'category', 'list'];
    protected $noNeedRight = '*';

    /**
     * 服务列表
     * 
     * @ApiTitle    (获取服务列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="is_recommend", type="integer", required=false, description="是否推荐:0=否,1=是")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "服务ID",
            "name": "服务名称",
            "icon": "图标",
            "cover_image": "封面图"
          }]
        }
      })
     */
    public function list()
    {
        $isRecommend = $this->request->get('is_recommend');
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $where = ['status' => 'normal'];
        if($isRecommend == 1) {
            $where['is_recommend'] = $isRecommend;
        }
        
        $total = Db::name('service')
            ->where($where)
            ->count();
            
        $list = Db::name('service')
            ->where($where)
            ->field(['id', 'name', 'icon', 'cover_image'])
            ->order('weigh DESC, id DESC')
            ->page($page, $pageSize)
            ->select();
        // 处理图片完整路径
        foreach($list as &$item) {
            $item['icon'] = cdnurl($item['icon']);
            $item['cover_image'] = cdnurl($item['cover_image']);
        }
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }

    /**
     * 老师服务列表
     * 
     * @ApiTitle    (老师服务项目列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="type", type="string", required=false, description="类型:recommend=推荐,hot=最热,nearby=附近", default="recommend")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams   (name="service_id", type="integer", required=false, description="服务ID")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "service_name": "服务名称",
            "icon": "图标",
            "cover_image": "封面图",
            "price": "价格",
            "description": "描述",
            "teacher_name": "讲师姓名",
            "teacher_avatar": "讲师头像",
            "teacher_bio": "讲师简介",
            "distance": "距离 nearby类型时返回"
          }]
        }
      })
     */
    public function index()
    {
        $type = $this->request->get('type', 'recommend');
        $keyword = $this->request->get('keyword', '');
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        $serviceId = $this->request->get('service_id', 0);
        // 基础查询条件
        $where = ['s.status' => 'normal'];

        // 添加服务ID查询条件
        if ($serviceId) {
            $where['s.id'] = $serviceId;
        }
        if($keyword){
            $where[] = function($query) use ($keyword) {
                $query->where('s.name', 'like', "%{$keyword}%")
                    ->whereOr('u.nickname', 'like', "%{$keyword}%");
            };
        }
        // 记录搜索历史
        if ($keyword && $this->auth->id) {
            SearchLog::record($this->auth->id, $keyword, 'service');
        }
        // 构建基础字段
        $fields = [
            'st.id',
            'st.service_id',
            'st.teacher_id',
            's.name as service_name',
            's.icon',
            's.cover_image',
            'st.price',
            's.description',
            'u.nickname as teacher_name',
            'u.avatar as teacher_avatar',
            'u.bio as teacher_bio'
        ];
        $lat = $this->auth->latitude;
        $lng = $this->auth->longitude;
        // 如果是附近类型，添加距离计算字段
        if($type == 'nearby') {
            if(!$this->auth->latitude || !$this->auth->longitude){
                $this->error('请先获取位置信息');
            }
        }
        
        // 构建查询
        $list = Db::name('service_teacher')->alias('st')
            ->join('service s', 's.id = st.service_id')
            ->join('user u', 'u.id = st.teacher_id')
            ->where(function($query) use ($type, $where, $lat, $lng) {
                // 基础条件
                $query->where('u.is_teacher', 1)
                    ->where('st.status', 'normal')
                    ->where($where);
                
                // 类型条件
                switch($type) {
                    case 'recommend':
                        $query->where('st.is_recommend', '1');
                        break;
                    case 'hot':
                        $query->where('st.is_hot', '1');
                        break;
                    case 'nearby':
                        // 添加城市筛选条件，假设用户城市在 $this->auth->city
                        if (isset($this->auth->city) && !empty($this->auth->city)) {
                            $query->where('u.city', $this->auth->city);
                        }
                        // 添加距离计算字段
                        $query->field("ROUND(
                            6378.138 * 2 * ASIN(
                                SQRT(
                                    POW(SIN(($lat * PI() / 180 - u.latitude * PI() / 180) / 2),2)
                                    + COS($lat * PI() / 180) * COS(u.latitude * PI() / 180)
                                    * POW(SIN(($lng * PI() / 180 - u.longitude * PI() / 180) / 2),2)
                                )
                            )
                        ,2) as distance");
                        
                        // 设置排序
                        $query->order('distance ASC, st.weigh DESC');
                        break;
                }
                
                // 非附近类型的排序
                if($type != 'nearby') {
                    $query->order('st.weigh DESC, st.id DESC');
                }
            })
            ->field([
                'st.id',
                'st.service_id',
                'st.teacher_id',
                's.name as service_name',
                's.icon',
                's.cover_image',
                'st.price',
                's.description',
                'u.nickname as teacher_name',
                'u.avatar as teacher_avatar',
                'u.bio as teacher_bio'
            ])->page($page, $pageSize)->select();

        $total = Db::name('service_teacher')->alias('st')
            ->join('service s','s.id = st.service_id')
            ->join('user u', 'u.id = st.teacher_id')
            ->where('u.is_teacher', 1)
            ->where('st.status', 'normal')
            ->where($where)
            ->where(function($query) use ($type, $where, $lat, $lng) {
                // 基础条件
                $query->where('u.is_teacher', 1)
                    ->where('st.status', 'normal')
                    ->where($where);
                
                // 类型条件
                switch($type) {
                    case 'recommend':
                        $query->where('st.is_recommend', '1');
                        break;
                    case 'hot':
                        $query->where('st.is_hot', '1');
                        break;
                }
            })
            ->count();
        // 处理图片完整路径
        foreach($list as &$item) {
            $item['icon'] = cdnurl($item['icon']);
            $item['cover_image'] = cdnurl($item['cover_image']);
            $item['teacher_avatar'] = cdnurl($item['teacher_avatar']);
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }

    /**
     * 服务详情
     * 
     * @ApiTitle    (服务项目详情)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="服务老师关联ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": "关联ID",
          "service_id": "服务ID",
          "service_name": "服务名称",
          "icon": "图标",
          "cover_image": "封面图",
          "images": "轮播图列表",
          "price": "价格",
          "description": "描述",
          "content": "内容",
          “has_voucher”："是否有可用代金券",
          "teacher": {
            "id": "讲师ID",
            "nickname": "讲师姓名",
            "avatar": "讲师头像",
            "bio": "讲师简介",
            "gender": "性别",
            "is_follow": "是否已关注",
            "is_me": "是否是自己"
          }
        }
      })
     */
    public function detail($id)
    {
        // 查询服务和老师信息
        $detail = Db::name('service_teacher')->alias('st')
            ->join('service s', 's.id = st.service_id')
            ->join('user u', 'u.id = st.teacher_id')
            ->where('st.id', $id)
            ->where('st.status', 'normal')
            ->where('u.is_teacher', 1)
            ->field([
                'st.id',
                'st.service_id',
                's.name as service_name',
                's.icon',
                's.cover_image',
                's.images',
                'st.price',
                's.description',
                's.content',
                'u.id as teacher_id',
                'u.nickname as teacher_nickname',
                'u.avatar as teacher_avatar',
                'u.bio as teacher_bio',
                'u.gender as teacher_gender'
            ])
            ->find();
            
        if(!$detail){
            $this->error('服务不存在或已下架');
        }
        // 处理图片完整路径
        $detail['icon'] = cdnurl($detail['icon']);
        $detail['cover_image'] = cdnurl($detail['cover_image']);
        
        // 轮播图字符串转数组并处理完整路径
        $detail['images'] = $detail['images'] ? array_map(function($image) {
            return cdnurl($image);
        }, explode(',', $detail['images'])) : [];
        
        // 检查是否有可用代金券
        $detail['has_voucher'] = false;
        if($this->auth->id) {
            $voucher = Db::name('user_voucher')
                ->where('user_id', $this->auth->id)
                ->where('status', 0) // 未使用
                ->where('expire_time', '>', time()) // 未过期
                ->whereRaw("FIND_IN_SET('{$detail['teacher_id']}', teacher_ids)")
                ->find();
            $detail['has_voucher'] = $voucher ? true : false;
        }
        $detail['teacher_avatar'] = $detail['teacher_avatar'] ? $detail['teacher_avatar'] : '/uploads/20250519/2a71134e114fc9da0883c8627eff9efa.png';
        // 格式化老师信息
        $is_my = false;
        if($this->auth->id == $detail['teacher_id']) {
            $is_my = true;
        }
        $teacher = [
            'id' => $detail['teacher_id'],
            'nickname' => $detail['teacher_nickname'],
            'avatar' => cdnurl($detail['teacher_avatar']),
            'bio' => $detail['teacher_bio'],
            'gender' => $detail['teacher_gender'],
            'is_follow' => false,
            'is_my' => $is_my
        ];
        
        // 如果用户已登录,查询是否关注了老师
        if($this->auth->id){
            $follow = Db::name('user_follow')
                ->where('user_id', $this->auth->id)
                ->where('teacher_id', $teacher['id'])
                ->find();
            $teacher['is_follow'] = $follow ? true : false;
        }
        
        // 删除多余字段
        unset($detail['teacher_id']);
        unset($detail['teacher_nickname']);
        unset($detail['teacher_avatar']);
        unset($detail['teacher_bio']);
        unset($detail['teacher_gender']);
        
        $detail['teacher'] = $teacher;
        
        $this->success('', $detail);
    }
    
    /**
     * 更新位置
     * 
     * @ApiTitle    (更新位置信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="latitude", type="string", required=true, description="纬度")
     * @ApiParams   (name="longitude", type="string", required=true, description="经度")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": null
      })
     */
    public function updateLocation()
    {
        $this->auth->check();
        
        $latitude = $this->request->post('latitude');
        $longitude = $this->request->post('longitude');
        
        if(!$latitude || !$longitude){
            $this->error('参数错误');
        }
        try {
            // 获取地址信息
            $addressInfo = \app\common\library\Location::getAddressByLocation($latitude, $longitude);
            // 更新用户表
            $updateData = [
                'latitude' => $latitude,
                'longitude' => $longitude,
                'location_update_time' => time()
            ];
           
            // 如果获取到地址信息则一并更新
            if ($addressInfo) {
                $updateData['address'] = $addressInfo['address'];
                $updateData['formatted_address'] = $addressInfo['formatted_address'];
                $updateData['city'] = $addressInfo['city'];
            }
            
            $result = Db::name('user')->where('id', $this->auth->id)->update($updateData);
            
            if($result){
                // 同步更新当前登录用户信息
                $this->auth->latitude = $latitude;
                $this->auth->longitude = $longitude;
                $this->auth->location_update_time = time();
                if ($addressInfo) {
                    $this->auth->address = $addressInfo['address'];
                    $this->auth->formatted_address = $addressInfo['formatted_address'];
                }
                
                $this->success('更新成功',['address' => $updateData['address'],'formatted_address' => $updateData['formatted_address']]);
            }else{
                $this->error('更新失败');
            }
        } catch (\think\exception\PDOException $e) {
            $this->error('更新失败:'.$e->getMessage());
        }
    }

    /**
     * 创建服务订单
     * 
     * @ApiTitle    (创建服务订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="service_teacher_id", type="integer", required=true, description="服务老师关联ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "order_no": "订单编号",
          "amount": "订单金额"
        }
      })
     */
    public function createOrder()
    {
        $this->auth->check();
        
        $serviceTeacherId = $this->request->post('service_teacher_id');
        
        if(!$serviceTeacherId){
            $this->error('参数错误');
        }
        
        // 查询服务信息
        $serviceTeacher = Db::name('service_teacher')->alias('st')
            ->join('service s', 's.id = st.service_id')
            ->join('user u', 'u.id = st.teacher_id')
            ->where('st.id', $serviceTeacherId)
            ->where('st.status', 'normal')
            ->where('u.is_teacher', 1)
            ->field([
                'st.*',
                's.name as service_name',
                'u.nickname as teacher_name'
            ])
            ->find();
            
        if(!$serviceTeacher){
            $this->error('服务不存在或已下架');
        }
        
        Db::startTrans();
        try {
            // 生成订单
            $orderNo = date('YmdHis') . mt_rand(1000, 9999);
            $orderId = Db::name('service_order')->insertGetId([
                'order_no' => $orderNo,
                'user_id' => $this->auth->id,
                'service_id' => $serviceTeacher['service_id'],
                'teacher_id' => $serviceTeacher['teacher_id'],
                'amount' => $serviceTeacher['price'],
                'status' => 0, // 0=待支付,1=已支付,2=已完成,3=已取消
                'createtime' => time(),
                'updatetime' => time()
            ]);
            
            if(!$orderId){
                throw new \Exception('创建订单失败');
            }
            
            Db::commit();
            
            $this->success('创建成功', [
                'order_no' => $orderNo,
                'order_id' => $orderId,
                'amount' => $serviceTeacher['price']
            ]);
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 我的服务订单
     * 
     * @ApiTitle    (我的服务订单列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="status", type="string", required=false, description="状态:0=待支付,1=已支付,2=已完成,3=已取消,全部=all")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词,支持服务名称/老师昵称/订单号")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success", 
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "订单ID",
            "order_no": "订单编号",
            "service_name": "服务名称", 
            "teacher_name": "讲师姓名",
            “cover_image” : "封面图",
            "amount": "订单金额",
            "status": "订单状态:0=待支付,1=已支付,2=已完成,3=已取消",
            "createtime": "创建时间"
          }]
        }
      })
     */
    public function myOrders()
    {
        $this->auth->check();
        
        $params = $this->request->get();
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        $keyword = $this->request->get('keyword', '');
        $teacher_id = $this->request->get('teacher_id', '');
        $where = [];
        if($params['status'] != 'all' && $params['status'] !== null && $params['status']!== ''){
            $where['o.status'] = ['=', intval($params['status'])];
        }
        if($teacher_id){
            $where['o.teacher_id'] = ['=', intval($teacher_id)];
        }
        // 添加关键词搜索
        if($keyword){
            $where[] = function($query) use ($keyword) {
                $query->where('s.name', 'like', "%{$keyword}%")
                    ->whereOr('u.nickname', 'like', "%{$keyword}%")
                    ->whereOr('o.order_no', 'like', "%{$keyword}%");
            };
            
            // 记录搜索历史
            SearchLog::record($this->auth->id, $keyword, 'service_order');
        }
        $query = Db::name('service_order')->alias('o')
            ->join('service s', 's.id = o.service_id')
            ->join('user u', 'u.id = o.teacher_id')
            ->where('o.user_id', $this->auth->id)
            ->where($where)
            ->field([
                'o.*',
                's.name as service_name',
                's.cover_image',
                'u.nickname as teacher_name'
            ])
            ->order('o.id DESC');
            
        $list = $query->page($page, $pageSize)->select();
        $total = Db::name('service_order')->alias('o')
            ->join('service s', 's.id = o.service_id')
            ->join('user u', 'u.id = o.teacher_id')
            ->where('o.user_id', $this->auth->id)
            ->where($where)->count();
        // 格式化时间
        foreach($list as &$item){
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['cover_image'] = cdnurl($item['cover_image']);
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }
    
    /**
     * 订单详情
     * 
     * @ApiTitle    (订单详情)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": "订单ID",
          "order_no": "订单编号",
          "service_name": "服务名称",
          "service_icon": "服务图标",
          "service_cover": "服务封面",
          "service_description": "服务描述",
          "teacher_name": "讲师姓名",
          "teacher_avatar": "讲师头像",
          "teacher_bio": "讲师简介",
          "amount": "订单金额",
          "status": "订单状态:0=待支付,1=已支付,2=已完成,3=已取消",
          "pay_type": "支付方式:wechat=微信支付,alipay=支付宝支付,voucher=代金券支付",
          "pay_time": "支付时间",
          "complete_time": "完成时间",
          "createtime": "创建时间"
        }
      })
     */
    public function orderDetail($id)
    {
        $this->auth->check();
        
        $order = Db::name('service_order')->alias('o')
            ->join('service s', 's.id = o.service_id')
            ->join('user u', 'u.id = o.teacher_id')
            ->where('o.id', $id)
            ->where('o.user_id', $this->auth->id)
            ->field([
                'o.*',
                's.name as service_name',
                's.icon as service_icon',
                's.cover_image as service_cover',
                's.description as service_description',
                'u.nickname as teacher_name',
                'u.avatar as teacher_avatar',
                'u.bio as teacher_bio'
            ])
            ->find();
            
        if(!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] == 0) {
            $order['pay_end_time'] = $order['createtime'] + 7200; // 创建时间加2小时
        }
        // 处理图片完整路径
        $order['service_icon'] = cdnurl($order['service_icon']);
        $order['service_cover'] = cdnurl($order['service_cover']);
        $order['teacher_avatar'] = cdnurl($order['teacher_avatar']);
        $order['createtime'] = date('Y-m-d H:i:s', $order['createtime']);
        if($order['pay_time']){
            $order['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
        }
        if($order['complete_time']){
            $order['complete_time'] = date('Y-m-d H:i:s', $order['complete_time']);
        }
        
        $this->success('', $order);
    }
    
    
    /**
     * 代金券支付
     * 
     * @ApiTitle    (使用代金券支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_no", type="string", required=true, description="订单编号")
     * @ApiReturn   ({
        "code": 1,
        "msg": "支付成功",
        "data": null
      })
     */
    public function voucherPay()
    {
        $this->auth->check();
        
        $orderNo = $this->request->post('order_no');
        
        // 查询订单
        $order = Db::name('service_order')->where([
            'order_no' => $orderNo,
            'user_id' => $this->auth->id,
            'status' => 0
        ])->find();

        if (!$order) {
            $this->error('订单不存在或已支付');
        }

        // 查询可用代金券
        $voucher = Db::name('user_voucher')
            ->where([
                'user_id' => $this->auth->id,
                'status' => 0
            ])
            ->where('expire_time', '>', time())
            ->whereRaw("FIND_IN_SET('{$order['teacher_id']}', teacher_ids)")
            ->order('expire_time ASC') // 优先使用快过期的
            ->find();

        if (!$voucher) {
            $this->error('没有可用的代金券');
        }
        Db::startTrans();
        try {
            // 更新订单状态
            $result = Db::name('service_order')->where('id', $order['id'])->update([
                'status' => 1, // 已支付
                'pay_time' => time(),
                'updatetime' => time(),
                'pay_type' => 'voucher',
                'voucher_id' => $voucher['id']
            ]);
            
            if (!$result) {
                throw new \Exception('更新订单状态失败');
            }

            // 更新代金券状态
            $result = Db::name('user_voucher')->where('id', $voucher['id'])->update([
                'status' => 1, // 已使用
                'use_time' => time(),
                'service_order_id' => $order['id']
            ]);

            if (!$result) {
                throw new \Exception('更新代金券状态失败');
            }

            // 给老师加余额
            // $result = Db::name('user')->where('id', $order['teacher_id'])->setInc('money', $order['amount']);
            // if (!$result) {
            //     throw new \Exception('更新老师余额失败');
            // }

            // // 记录老师资金变动日志
            // $result = Db::name('user_money_log')->insert([
            //     'user_id' => $order['teacher_id'],
            //     'money' => $order['amount'],
            //     'before' => Db::name('user')->where('id', $order['teacher_id'])->value('money') - $order['amount'],
            //     'after' => Db::name('user')->where('id', $order['teacher_id'])->value('money'),
            //     'memo' => '服务单号：'. $order['order_no'] . '(代金券支付)',
            //     'type' => 'service_income',
            //     'service_order_id' => $order['id'],
            //     'createtime' => time()
            // ]);

            if (!$result) {
                throw new \Exception('记录资金日志失败');
            }

            Db::commit();
            $this->success('支付成功');
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('支付失败：' . $e->getMessage());
        }
    }
    
    /**
     * 订单支付
     * 
     * @ApiTitle    (服务订单支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_no", type="string", required=true, description="订单编号")
     * @ApiParams   (name="pay_type", type="string", required=true, description="支付方式:wechat=微信支付,alipay=支付宝支付")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "type": "wechat",      // 支付方式
          "params": {}           // 支付参数
        }
      })
     */
        public function pay()
        {
            $this->auth->check();
            
            $orderNo = $this->request->post('order_no');
            $payType = $this->request->post('pay_type');
            
            // 验证支付方式
            if (!in_array($payType, ['wechat', 'alipay'])) {
                $this->error('不支持的支付方式');
            }
            
            $order = Db::name('service_order')->where([
                'order_no' => $orderNo,
                'user_id' => $this->auth->id,
                'status' => 0
            ])->find();
    
            if (!$order) {
                $this->error('订单不存在或已支付');
            }
            if($order['amount'] <= 0){
                $this->error('订单金额错误');
            }
            try {
                // 创建支付
                $notify_url = request()->domain() . '/api/payment/notifyService/paytype/' . $payType;
                $result = \addons\epay\library\Service::submitOrder($order['amount'], $order['order_no'], 
                    $payType, '服务订单', $notify_url, '','app');
                    
                if (!$result) {
                    $this->error('创建支付失败');
                }
                
                $this->success('', [
                    'type' => $payType,
                    'params' => $payType == 'wechat' ? json_decode($result, true) : $result
                ]);
            } catch (\think\exception\PDOException $e) {
                $this->error('支付失败：' . $e->getMessage());
            }
        }
        
        /**
         * 关注/取关老师
         * 
         * @ApiTitle    (关注/取关老师)
         * @ApiMethod   (POST)
         * @ApiParams   (name="teacher_id", type="integer", required=true, description="老师ID")
         * @ApiParams   (name="type", type="string", required=true, description="操作类型:follow=关注,unfollow=取关")
         * @ApiReturn   ({
            "code": 1,
            "msg": "success",
            "data": {
              "is_follow": "是否已关注"
            }
          })
         */
        public function follow()
        {
            $this->auth->check();
            
            $teacherId = $this->request->post('teacher_id');
            $type = $this->request->post('type');
            
            if(!$teacherId || !in_array($type, ['follow', 'unfollow'])){
                $this->error('参数错误');
            }
            
            // 检查老师是否存在
            $teacher = \think\Db::name('user')
                ->where('id', $teacherId)
                ->where('is_teacher', 1)
                ->find();
                
            if(!$teacher){
                $this->error('老师不存在');
            }
            
            // 检查是否已关注
            $follow = \think\Db::name('user_follow')
                ->where('user_id', $this->auth->id)
                ->where('teacher_id', $teacherId)
                ->find();
                
            if($type == 'follow'){
                // 关注
                if(!$follow){
                    $result = \think\Db::name('user_follow')->insert([
                        'user_id' => $this->auth->id,
                        'teacher_id' => $teacherId,
                        'createtime' => time()
                    ]);
                    if(!$result){
                        $this->error('关注失败');
                    }
                }
                $isFollow = true;
            }else{
                // 取关
                if($follow){
                    $result = \think\Db::name('user_follow')
                        ->where('id', $follow['id'])
                        ->delete();
                    if(!$result){
                        $this->error('取关失败');
                    }
                }
                $isFollow = false;
            }
            
            $this->success('操作成功', [
                'is_follow' => $isFollow
            ]);
        }
        
        /**
         * 取消订单
         * 
         * @ApiTitle    (取消服务订单)
         * @ApiMethod   (POST)
         * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
         * @ApiReturn   ({
            "code": 1,
            "msg": "取消成功",
            "data": null
          })
         */
        public function cancelOrder()
        {
            $this->auth->check();
            
            $id = $this->request->post('id');
            
            $order = Db::name('service_order')->where([
                'id' => $id,
                'user_id' => $this->auth->id,
                'status' => 0  // 只能取消未支付的订单
            ])->find();
    
            if (!$order) {
                $this->error('订单不存在或无法取消');
            }
    
            Db::startTrans();
            try {
                // 更新订单状态为已取消
                $result = Db::name('service_order')->where('id', $id)->update([
                    'status' => 3,
                    'updatetime' => time()
                ]);
                
                if (!$result) {
                    throw new \Exception('取消订单失败');
                }
                
                // 创建系统消息
                \app\common\model\SystemMessage::create([
                    'user_id' => $order['user_id'],
                    'type' => 'service',
                    'title' => '订单已取消',
                    'content' => "您的服务订单 {$order['order_no']} 已取消",
                    'order_id' => $order['id'],
                    'order_no' => $order['order_no']
                ]);
    
                Db::commit();
                $this->success('取消成功');
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                $this->error('取消订单失败：' . $e->getMessage());
            }
        }

        /**
         * 老师主页
         * 
         * @ApiTitle    (获取老师主页信息)
         * @ApiMethod   (GET)
         * @ApiParams   (name="teacher_id", type="integer", required=true, description="老师ID")
         * @ApiReturn   ({
            "code": 1,
            "msg": "success",
            "data": {
              "id": "老师ID",
              "nickname": "昵称",
              "avatar": "头像",
              "gender": "性别:0=男,1=女,2=未知",
              "bio": "个人简介",
              "order_count": "累计接单量",
              "is_follow": "是否已关注",
              "services": [{
                "id": "关联ID",
                "service_name": "服务名称",
                "icon": "图标",
                "cover_image": "封面图",
                "price": "价格",
                "description": "描述",
                "is_recommend": "是否推荐",
                "is_hot": "是否热门"
              }]
            }
          })
         */
        public function teacherHome()
        {
            $teacherId = $this->request->get('teacher_id');
            
            if(!$teacherId){
                $this->error('参数错误');
            }
            
            // 查询老师基本信息
            $teacher = Db::name('user')
                ->where('id', $teacherId)
                ->where('is_teacher', 1)
                ->field([
                    'id',
                    'nickname',
                    'avatar',
                    'gender',
                    'bio'
                ])
                ->find();
                
            if(!$teacher){
                $this->error('老师不存在');
            }
            $teacher['avatar'] = $teacher['avatar'] ? $teacher['avatar'] : '/uploads/20250519/2a71134e114fc9da0883c8627eff9efa.png';
            // 处理老师头像
            $teacher['avatar'] = cdnurl($teacher['avatar']);
            
            // 查询累计接单量
            $teacher['order_count'] = Db::name('service_order')
                ->where('teacher_id', $teacherId)
                ->where('status', 'in', [1,2]) // 已支付和已完成的订单
                ->count();
                
            // 查询是否关注
            $teacher['is_follow'] = false;
            if($this->auth->id){
                $follow = Db::name('user_follow')
                    ->where('user_id', $this->auth->id)
                    ->where('teacher_id', $teacherId)
                    ->find();
                $teacher['is_follow'] = $follow ? true : false;
            }
            
            // 查询老师的服务列表
            $services = Db::name('service_teacher')->alias('st')
                ->join('service s', 's.id = st.service_id')
                ->where('st.teacher_id', $teacherId)
                ->where('st.status', 'normal')
                ->field([
                    'st.id',
                    's.name as service_name',
                    's.icon',
                    's.cover_image',
                    'st.price',
                    's.description',
                    'st.is_recommend',
                    'st.is_hot'
                ])
                ->order('st.weigh DESC, st.id DESC')
                ->select();
                
            // 处理服务图片
            foreach($services as &$service) {
                $service['icon'] = cdnurl($service['icon']);
                $service['cover_image'] = cdnurl($service['cover_image']);
            }
                
            $teacher['services'] = $services;
            
            $this->success('', $teacher);
        }

    /**
     * 完成服务订单
     * 
     * @ApiTitle    (完成服务订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "完成成功",
        "data": null
      })
     */
    public function completeOrder()
    {
        $this->auth->check();
        
        $id = $this->request->post('id');
        
        $order = Db::name('service_order')->where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => 1  // 只能完成已支付的订单
        ])->find();

        if (!$order) {
            $this->error('订单不存在或无法完成');
        }

        Db::startTrans();
        try {
            // 更新订单状态为已完成
            $result = Db::name('service_order')->where('id', $id)->update([
                'status' => 2,
                'complete_time' => time(),
                'updatetime' => time()
            ]);
            $res = Db::name('user')->where('id', $order['teacher_id'])->setInc('money', $order['amount']);
            if(!$res) {
                throw new \Exception('更新老师余额失败');
            }
            
            // 记录老师资金变动日志
            $result = Db::name('user_money_log')->insert([
                'user_id' => $order['teacher_id'],
                'money' => $order['amount'],
                'before' => Db::name('user')->where('id', $order['teacher_id'])->value('money') - $order['amount'],
                'after' => Db::name('user')->where('id', $order['teacher_id'])->value('money'),
                'memo' => '服务单号：'. $order['order_no'],
                'type' => 'service_income',
                'service_order_id' => $order['id'],
                'createtime' => time()
            ]);
            if (!$result) {
                throw new \Exception('完成订单失败');
            }
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order['user_id'],
                'type' => 'service',
                'title' => '订单已完成',
                'content' => "您的服务订单 {$order['order_no']} 已完成",
                'order_id' => $order['id'],
                'order_no' => $order['order_no']
            ]);

            Db::commit();
            $this->success('完成成功');
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('完成订单失败：' . $e->getMessage());
        }
    }
}